using UnityEngine;

namespace Core
{
    public class InputComponent : Entity, IUpdate
    {
        float sign, angle;
        Vector3 inputDelta = Vector3.zero;
        Vector3 delta = default;
        Vector3 forward;
        void IUpdate.Update()
        {
            if (Player.Instance == null)
                return;

            UpdateDelta();
            var unit = Player.Instance.GetParent<Unit>();
            var stateMachineComponent = unit.GetComponent<StateMachineComponent>();

            if (stateMachineComponent.State == StateType.Idle || stateMachineComponent.State == StateType.Move)
            {
                stateMachineComponent.ChangedState(delta == Vector3.zero ? StateType.Idle : StateType.Move);
            }

            if (stateMachineComponent.State != StateType.Move)
                return;

            // 获取摄像机当前方向
            forward = unit.GetComponent<CameraComponent>().Forward;
            sign = Mathf.Sign(delta.x);
            angle = Vector3.Angle(delta, Vector3.forward) * sign;
            // 计算单位朝向
            forward = Quaternion.AngleAxis(angle, Vector3.up) * forward;
            var component = unit.GetComponent<MoveComponent>();
            component.SetDirection(forward);
            // 设置单位移动速度
            component.SetSpeed(delta.sqrMagnitude);
            stateMachineComponent.ChangedState(StateType.Move);
        }

        public void SetDelta(Vector3 delta)
        {
            inputDelta = delta;
        }

        void UpdateDelta()
        {
#if UNITY_EDITOR
            delta.Set(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
#endif
            if (inputDelta != Vector3.zero)
            {
                delta = inputDelta;
            }
        }
    }
}